import os
import utils
import collect
from openpyxl import Workbook
from openpyxl.utils import get_column_letter
from openpyxl.styles import PatternFill, Border, Side, Alignment
import datetime


today = datetime.date.today()  # 今天
yest = today - datetime.timedelta(days=1)


fill_date = PatternFill(
    fill_type='solid', start_color='D9FDE900', end_color='D9FDE900')
fill_main = PatternFill(
    fill_type='solid', start_color='C6FDCC00', end_color='C6FDCC00')
fill_alt = PatternFill(
    fill_type='solid', start_color='BCD7E400', end_color='BCD7E400')

thin = Side(border_style="thin", color="000000")
border_normal = Border(top=thin, bottom=thin, left=thin, right=thin)
align_header = Alignment(horizontal='center')
align_header_v = Alignment(vertical='center', wrap_text=True)


def save_excel(workbook, name):
    filename = '{}.xlsx'.format(name)
    try:
        workbook.save(filename)
        workbook.close()
    except PermissionError:
        print('无法写入{}，请检查是否在Excel中打开了文件，如有需要请另存为并关闭'.format(filename))

# 设置单元格宽度
def set_columns_width(sheet, columns_width):
    for index, width in enumerate(columns_width):
        sheet.column_dimensions[get_column_letter(index + 1)].width = width

# 拼接基本信息
def get_basic_data(b):
    return [b.get('nickname'), b.get('gh_id')]

def set_border(rows):
    for row in rows:
        for cell in row:
            cell.border = border_normal


def set_styles(rows, fill=None, alignment=None):
    for row in rows:
        for cell in row:
            if fill:
                cell.fill = fill
            if alignment:
                cell.alignment = alignment


# 生成表格
class ReportGenerator:
    def __init__(self, library, date_to_report):
        """
        :param utils.AccountLibrary library:
        :param date_to_report:
        """
        self.date = date_to_report
        self.library = library
        self.gh_id = None

    # 读取基础信息
    def get_basic(self, gh_id):
        date = utils.get_yesterday()
        return utils.get_json_file(gh_id, date, 'basic.json')

    # 读取累计数据
    def get_user_info(self, gh_id):
        return utils.get_json_file(gh_id, self.date, 'app-game-info-users.json')

    # 读取流量主数据
    def get_publish_info(self, gh_id):
        return utils.get_json_file(gh_id, self.date, 'app-publish-info.json')

    def save_excel(self, workbook, name):
        filename = 'output/{} {}.xlsx'.format(self.date, name)
        try:
            workbook.save(filename)
            workbook.close()
        except PermissionError:
            print('无法写入{}，请检查是否在Excel中打开了文件，如有需要请另存为并关闭'.format(filename))

    def make_today_ad(self, workbook,y):
        os.makedirs('output', exist_ok=True)
        self.make_littleGame_data(workbook,y)


    def make_littleGame_data(self, workbook,y):
        sheet1 = workbook.create_sheet(index=y,title='{0}'.format(self.date))
        set_columns_width(
            sheet1, [20, 16, 18, 18, 18, 18, 18, 12, 12, 12])
        sheet1.append(['日期', self.date])
        sheet1.append(['名称', '原始ID', '累计注册用户数', '活跃用户数', '新增注册用户数', '分享用户数', '活跃用户留存(%)',
                      '曝光量', '点击量', '广告收入(元)'])
        row_index = 2
        for gh_id in self.library.get_account_list():
            bb = self.get_basic(gh_id)
            a = self.get_user_info(gh_id)
            c = self.get_publish_info(gh_id)
            sheet1.append(get_basic_data(bb) + [
                a.get("Cumulative_number"), a.get("active_users"), a.get("new_registered_users"),
                a.get("Shared_Users"), a.get("New_User_Retention"), c.get("Exposure"), c.get("click"), c.get("income")
            ])
        sheet1['A1'].fill = fill_date
        set_styles(sheet1['A2:J2'], fill_main, align_header)
        set_styles(sheet1['A2:J{}'.format(row_index)], alignment=align_header_v)
        save_excel(workbook, "output/{} 获取的小游戏数据".format(utils.get_today()))
        for gh_id in self.library.get_account_list():
            os.remove('data/{0}/{1}/app-game-info-users.json'.format(gh_id, self.date))
            os.remove('data/{0}/{1}/app-publish-info.json'.format(gh_id, self.date))


if __name__ == '__main__':
    print("获取本月小游戏数据")
    aa = []
    for i in range(1, 32):
        date_time = today - datetime.timedelta(days=i)
        if str(date_time)[8:] == "01":
            aa.append(str(date_time))
            break
        else:
            aa.append(str(date_time))
    y = 0
    collect.test_collect(None)
    workbook = Workbook()
    sheet = workbook.active
    for a in aa:
        reporter = ReportGenerator(
            utils.default_library(), a)
        reporter.make_today_ad(workbook,y)
        y += 1